package com.bg.print.controller;

import com.bg.print.entity.UserEntity;
import com.bg.print.service.UserService;
import com.bg.print.utils.PageUtils;
import com.bg.print.utils.R;
import com.bg.print.variable.Enabled;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;
import java.util.Objects;

import static com.bg.print.variable.Role.ROLE_BUYER;
import static com.bg.print.variable.Role.ROLE_MERCHANT;

/**
 * 用户
 *
 * @author liuxvru
 * @email liuxvru@163.com
 * @date 2024-03-25 17:50:46
 */
@Tag(name = "用户")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;


    /**
     * 列表
     */
    @Operation(summary = "列表")
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('ADMIN')")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = userService.queryPage(params);
        return R.ok().put("data", page);
    }


    /**
     * 信息
     */
    @Operation(summary = "信息")
    @GetMapping("/info")
    public R info(@AuthenticationPrincipal UserDetails userDetails) {
        UserEntity user = userService.getUserByUserDetails(userDetails);
        return R.ok().put("data", user);
    }

    @Operation(summary = "买家注册")
    @PostMapping("/buyer/save")
    public R buyerSave(@RequestBody UserEntity user) {
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        user.setPermissions(ROLE_BUYER.getRole());
        user.setEnabled(Enabled.USING.getCode());
        userService.save(user);
        return R.ok();
    }

    @Operation(summary = "商家注册")
    @PostMapping("/merchant/save")
    @PreAuthorize("hasAuthority('ADMIN')")
    public R merchantSave(@RequestBody UserEntity user) {
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        user.setPermissions(ROLE_MERCHANT.getRole());
        user.setEnabled(Enabled.USING.getCode());
        userService.save(user);
        return R.ok();
    }

    /**
     * 修改
     */
    @Operation(summary = "修改")
    @PutMapping("/update")
    public R update(@RequestBody UserEntity user, @AuthenticationPrincipal UserDetails userDetails) {
        if (Objects.equals(user.getAccount(), userDetails.getUsername())) {
            Integer ok = userService.updateByAccount(user);
            if (ok == 1)
                return R.ok();
            else
                return R.error(500, "修改错误");
        }
        return R.error(400, "没有权限");
    }

    @Operation(summary = "ADMIN修改")
    @PutMapping("/adminUp")
    @PreAuthorize("hasAuthority('ADMIN')")
    public R adminUp(@RequestBody UserEntity user) {
        boolean ok = userService.updateById(user);
        if (ok)
            return R.ok();
        else
            return R.error(500, "修改错误");
    }



    @Operation(summary = "根据id获取用户")
    @GetMapping("/getById/{id}")
    @PreAuthorize("hasAuthority('ADMIN')")
    public R getById(@PathVariable("id") Long id ) {
        UserEntity ok = userService.getById(id);
        if (ok!=null)
            return R.ok().put("data",ok);
        else
            return R.error(500, "参数错误");
    }

}
